/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.box.redis

import com.google.inject.Provider
import cool.taomu.box.inter.IDataSource
import javax.inject.Inject
import javax.inject.Named
import redis.clients.jedis.JedisPool
import redis.clients.jedis.JedisPoolConfig

abstract class AbsRedisJedisPoolProvider implements Provider<IDataSource> {
	@Inject
	@Named("redis.host")
	String host;
	@Inject
	@Named("redis.port")
	Integer port;
	@Inject
	@Named("redis.password")
	String password;
	@Inject
	@Named("redis.username")
	String username;
	@Inject
	@Named("redis.timeout")
	Integer timeout;

	abstract def void configure(JedisPoolConfig poolConfig);

	override get() {
		var jedisPoolConfig = new JedisPoolConfig();
		this.configure(jedisPoolConfig);
		var password = password;
		var user = username;
		var timeout = timeout;
		// LOG.info("创建Redis连接: {}:{}", host, port);
		var JedisPool pool;
		if (user === null) {
			if (password === null) {
				pool = new JedisPool(jedisPoolConfig, host, port);
			} else {
				pool = new JedisPool(jedisPoolConfig, host, port, timeout, password);
			}
		} else if (user !== null && password !== null) {
			pool = new JedisPool(jedisPoolConfig, host, port, timeout, user, password);
		}
		return new RedisDataSource(pool);
	}

}
